import { defineConfig, loadEnv } from 'vite'
import path from 'path'
import { createVuePlugin } from 'vite-plugin-vue2'
import envCompatible from 'vite-plugin-env-compatible'
import { createHtmlPlugin } from 'vite-plugin-html'
import { viteCommonjs } from '@originjs/vite-plugin-commonjs'
import qiankun from 'vite-plugin-qiankun'

// https://vitejs.dev/config/
export default defineConfig(({ command, mode }) => {
  const env = loadEnv(mode, process.cwd(), '')
  return {
    resolve: {
      alias: [
        {
          find: /^~/,
          replacement: ''
        },
        {
          find: '@',
          replacement: path.resolve(__dirname, 'src')
        },
        {
          find: 'vue$',
          replacement: path.resolve(__dirname, 'vue/dist/vue.esm.js')
        },
        {
          find: '@static',
          replacement: path.resolve(__dirname, 'src/static')
        },
        {
          find: '@component',
          replacement: path.resolve(__dirname, 'src/components')
        },
        {
          find: '@common',
          replacement: path.resolve(__dirname, 'src/components/common')
        },
        {
          find: '@assets',
          replacement: path.resolve(__dirname, 'src/assets')
        },
        {
          find: '@utils',
          replacement: path.resolve(__dirname, 'src/utils')
        }
      ],
      extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue']
    },
    define: {
      'process.env': env
    },
    plugins: [
      qiankun('yunying', {
        useDevMode: true
      }),
      createVuePlugin({ jsx: true }),
      viteCommonjs(),
      envCompatible(),
      createHtmlPlugin({
        inject: {
          data: {
            title: 'yunying-cli4'
          }
        }
      })
    ],
    base: '/',
    server: {
      host: env.VUE_APP_HOST,
      port: env.VUE_APP_PORT,
      strictPort: false,
      proxy: {
        '/api/polyv': {
          target: 'http://api.polyv.net',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api\/polyv/, '')
        },
        '/api/token/get_token': {
          target: 'http://192.168.1.62:8083/api',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, '')
        },
        '/api/token/refresh_token': {
          target: 'http://oldpc.dapengjiaoyu.com/api',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, '')
        },
        '/api': {
          target: env.VUE_APP_BASE_URL,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, '')
        }
      }
    },
    build: {}
  }
})
